<template>
<div>
    <el-upload
        action="#"
        list-type="picture-card"
        :file-list="fileList"
        :on-remove="handleRemove"
        :limit="1"
        :on-change="changeFile"
        :before-upload="beforeUpload"
        :on-preview="handlePreview"
        :http-request="upload"
        :class="{ disabled: fileComputed }">
        <i class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-progress
      v-if="showPercent"
      :percentage="percent"
      style="width: 180px"
    ></el-progress>
    <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
</div> 
</template>

<script>
    import COS from "cos-js-sdk-v5";
    const cos = new COS({
        SecretId: "AKIDTmpdARRAcnhMlumNhkW1HGyPaYFfohph",
        SecretKey: "cz5uSkmX1D9oCJAk47vUmmWzB6k8F5ex",
    });
    export default {
        data() {
          return {
            fileList: [],
            dialogImageUrl: '',
            dialogVisible: false,
            currentFileUid: null,
            showPercent: false,
            percent: 0,
          };
        },
        computed: {
            fileComputed() {
                return this.fileList.length === 1;
            }
        },
        methods: {
           //   预览
          handlePreview(file) {
              this.dialogImageUrl = file.url;
              this.dialogVisible = true;
          },
        //   删除
          handleRemove (file,fileList) {
              this.fileList = this.fileList.filter((item) => 
                  item.uid !== file.uid
              )
          },
        //   文件状态改变
          changeFile(file,fileList) {
              this.fileList = fileList.map( item => item)
          },
          // 上传前检查
          beforeUpload (file) {
            const type = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png'];
            if(!type.some( item => item === file.type)) {
                this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
                return false
            }
            const maxSize = 10 * 1024 * 1024
            if (file.size > maxSize) {
                this.$message.error('上传的图片大小不能大于5M')
                return false
            }

            this.currentFileUid = file.uid;
            this.showPercent = true;
            return true
          },
        //   传到腾讯云里
            upload (params) {
                if (params.file) {
                  cos.putObject(
                    {
                      Bucket: "yjh2022-1312328227" /* 填入您自己的存储桶，必须字段 */,
                      Region: "ap-beijing" /* 存储桶所在地域，例如ap-beijing，必须字段 */,
                      Key: params.file
                        .name /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
                      StorageClass: "STANDARD",
                      Body: params.file, // 上传文件对象
                      onProgress: (params) => {
                          this.percent = Math.floor(params.percent * 100)
                      }
                    },
                    (err, data) => {
                      if (!err && data.statusCode === 200) {
                          this.fileList = this.fileList.map( item => {
                              if (item.uid === this.currentFileUid) {
                                  return { url: 'http://' + data.Location, upload: true }
                              }
                              return item
                          })
                          setTimeout(() => {
                          this.showPercent = false; //隐藏进度条
                          this.percent = 0; //进度归0
                        }, 2000);
                      }
                    }
                  );
                }
            }
        }
        
        
    }
</script>

<style scoped>
    /deep/ .disabled .el-upload--picture-card {
      display: none;
    }
</style>